package cn.edu.cqu.fredyvia.forum.storage.service.impl;

import cn.edu.cqu.fredyvia.forum.config.AliyunOssConfig;
import cn.edu.cqu.fredyvia.forum.storage.service.AliyunOssStorageProvider;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Path;

@Slf4j

//@ConfigurationProperties(prefix = "storage.aliyun-oss",ignoreInvalidFields = true)
@Component
public class AliyunOssStorageProviderImpl implements AliyunOssStorageProvider {
    @Autowired
    AliyunOssConfig aliyunOssConfig;

    @Autowired
    OSS ossClient;

    //    String rolearn;
    //    String securityToken = getTmpUploadToken();
    // 创建OSSClient实例。
    //在这里使用临时访问凭证securityToken，应该不仅限于上传文件了


    @Override
    //我理解的basepath是目标存储空间bucketname下的一个目录，path是basepath目录下的具体文件路径
    public void save(File file, Path path) throws FileNotFoundException {
        if (file.isDirectory()) {
            throw new UnsupportedOperationException("暂时不支持文件夹上传");
        }
        log.info(path.toString());
        save(new FileInputStream(file),path);
    }

    @Override
    public void save(File file) throws FileNotFoundException {
        save(file,file.toPath().getFileName());
    }

    PutObjectRequest getPutObjectRequest(InputStream inputStream,Path path){
        return new PutObjectRequest(aliyunOssConfig.getBucketname(),String.valueOf(path.toString()), inputStream);
    }

    GetObjectRequest getGetObjectRequest(Path path){
        return new GetObjectRequest(aliyunOssConfig.getBucketname(), path.toString());
    }

    @Override
    public void save(InputStream inputStream, Path path) {
        PutObjectRequest putObjectRequest = getPutObjectRequest(inputStream,path);
        ossClient.putObject(putObjectRequest);
    }

//    @Override
//    public void save(Object o, Path path) throws FileNotFoundException {
//        PutObjectRequest putObjectRequest =
//                new PutObjectRequest(bucketname, basepath + "/" + path, Byte.p);
//        ossClient.putObject(putObjectRequest);
//    }

    @Override
    public void get(Path path, File to) {
//        File file = File.createTempFile("temp-file-name", ".tmp");
        ossClient.getObject(getGetObjectRequest(path), to);
    }

    @Override
    public void remove(Path path) {
        ossClient.deleteObject(aliyunOssConfig.getBucketname(), path.toString());
    }

    @Override
    //  移动文件到另一个路径
    //下载(旧)->上传(新)->删除(旧)
    public void move(Path sourcePath, Path destPath) throws IOException {
        File file = File.createTempFile("temp-file-name", ".tmp");
        get(sourcePath, file);
        save(file, destPath);
        remove(sourcePath);
        file.delete();
    }
//
//    @Override
//    // 获取上传临时token
//    // https://help.aliyun.com/document_detail/32016.html?spm=a2c4g.11186623.6.996.ceb314a0JAi7fb
//    public URL getTmpPostToken(Path path) {
//        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
//        IAcsClient client = new DefaultAcsClient(profile);
//        //构造请求，设置参数。关于参数含义和设置方法，请参见API参考。
//        AssumeRoleRequest request = new AssumeRoleRequest();
//        request.setRoleArn(rolearn);
//        request.setRoleSessionName("<RoleSessionName>");
//
//        //发起请求，并得到响应。
//        try {
//            AssumeRoleResponse response = client.getAcsResponse(request);
//            System.out.println(new Gson().toJson(response));
//        } catch (ServerException e) {
//            e.printStackTrace();
//        } catch (ClientException e) {
//            System.out.println("ErrCode:" + e.getErrCode());
//            System.out.println("ErrMsg:" + e.getErrMsg());
//            System.out.println("RequestId:" + e.getRequestId());
//        }
//        // 创建OSSClient实例。
//        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);
//        // 设置签名URL过期时间为3600秒（1小时）。
//        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
//        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
//        URL url = ossClient.generatePresignedUrl(bucketname, path.toString(), expiration);
//        return url;
//    }


//    @Override
//    public URL getTmpGetToken(Path path) {
//
//    }
}
